package cn.qrx.gateway.session;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author 屈燃希
 * @date 2025/10/2 10:35
 * @content
 */
public class GenericReferenceSessionFactory implements IGenericReferenceSessionFactory{


    private final Logger logger = LoggerFactory.getLogger(GenericReferenceSessionFactory.class);

    private final Configuration configuration;

    public GenericReferenceSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public Future<Channel> openSession() throws InterruptedException, ExecutionException {
        // 创建SessionServer实例

        SessionServer server = new SessionServer(configuration);

        // 使用固定大小为2的线程池提交服务器任务，并获取Future对象
        Future<Channel> future = Executors.newFixedThreadPool(2).submit(server);
        // 从Future中获取Channel对象
        Channel channel = future.get();

        // 检查Channel是否为空，如果为空则抛出运行时异常
        if (null == channel) throw new RuntimeException("netty server start error channel is null");

        // 循环检查Channel是否激活，直到Channel激活为止
        while (!channel.isActive()) {
            // 记录服务器启动信息
            logger.info("NettyServer启动服务 ...");
            // 线程休眠500毫秒
            Thread.sleep(500);
        }
        // 记录服务器启动完成信息，并输出本地地址
        logger.info("NettyServer启动服务完成 {}", channel.localAddress());

        // 使主线程无限期休眠，保持服务器运行
        Thread.sleep(Long.MAX_VALUE);
        return future;

    }
}
